package com.business.form.service;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.form.mapper.auto.FormFieldInfoValueMapper;
import com.business.form.model.auto.*;
import com.business.system.common.base.BaseService;
import com.business.system.common.support.Convert;
import com.business.system.model.custom.Tablepar;
import com.business.system.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.business.form.mapper.auto.FormFieldInfoMapper;

/**
 * 表单字段信息 FormFieldInfoService
 * @Title: FormFieldInfoService.java 
 * @Package com.business.form.service 
 * @author lujingyuan_自动生成
 * @email 
 * @date 2020-06-18 12:00:30  
 **/
@Service
public class FormFieldInfoService implements BaseService<FormFieldInfo, FormFieldInfoExample> {
	@Autowired
	private FormFieldInfoMapper formFieldInfoMapper;

	@Autowired
	private FormInfoService formInfoService;

	@Autowired
	private FormFieldInfoValueService formFieldInfoValueService;
	/**
	 * 分页查询
	 * @return
	 */
	 public PageInfo<FormFieldInfo> list(Tablepar tablepar, String name){
	        FormFieldInfoExample testExample=new FormFieldInfoExample();
	        testExample.setOrderByClause("id ASC");
	        if(name!=null&&!"".equals(name)){
	        	testExample.createCriteria().andFieldLabelLike("%"+name+"%");
	        }

	        PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
	        List<FormFieldInfo> list= formFieldInfoMapper.selectByExample(testExample);
	        PageInfo<FormFieldInfo> pageInfo = new PageInfo<FormFieldInfo>(list);
	        return  pageInfo;
	 }

	@Override
	public int deleteByPrimaryKey(String ids) {
				
			List<String> lista= Convert.toListStrArray(ids);
			FormFieldInfoExample example=new FormFieldInfoExample();
			example.createCriteria().andIdIn(lista);
			return formFieldInfoMapper.deleteByExample(example);
			
				
	}
	
	
	@Override
	public FormFieldInfo selectByPrimaryKey(String id) {
				
			return formFieldInfoMapper.selectByPrimaryKey(id);
				
	}

	
	@Override
	public int updateByPrimaryKeySelective(FormFieldInfo record) {
		return formFieldInfoMapper.updateByPrimaryKeySelective(record);
	}
	
	
	/**
	 * 添加
	 */
	@Override
	public int insertSelective(FormFieldInfo record) {
				
		//添加雪花主键id
		record.setId(SnowflakeIdWorker.getUUID());
			
				
		return formFieldInfoMapper.insertSelective(record);
	}
	
	
	@Override
	public int updateByExampleSelective(FormFieldInfo record, FormFieldInfoExample example) {
		
		return formFieldInfoMapper.updateByExampleSelective(record, example);
	}

	
	@Override
	public int updateByExample(FormFieldInfo record, FormFieldInfoExample example) {
		
		return formFieldInfoMapper.updateByExample(record, example);
	}

	@Override
	public List<FormFieldInfo> selectByExample(FormFieldInfoExample example) {
		
		return formFieldInfoMapper.selectByExample(example);
	}

	
	@Override
	public long countByExample(FormFieldInfoExample example) {
		
		return formFieldInfoMapper.countByExample(example);
	}

	
	@Override
	public int deleteByExample(FormFieldInfoExample example) {
		
		return formFieldInfoMapper.deleteByExample(example);
	}
	
	/**
	 * 检查name
	 * @param formFieldInfo
	 * @return
	 */
	public int checkNameUnique(FormFieldInfo formFieldInfo){
		FormFieldInfoExample example=new FormFieldInfoExample();
		example.createCriteria().andFieldLabelEqualTo(formFieldInfo.getFieldLabel());
		List<FormFieldInfo> list=formFieldInfoMapper.selectByExample(example);
		return list.size();
	}


	/**
	 *根据json字符串和表单id插入表单数据、表单字段数据、表单字段value数据
	 */
	public FormInfo addFormField(String formId, JSONArray arr){
		FormInfo form=null;
		if(StringUtils.isBlank(formId)){
			form=new FormInfo();

		}else{
			form=formInfoService.selectByPrimaryKey(formId);
		}
		if(form!=null&&form.getId()==null){
			form=new FormInfo();
			formInfoService.insertSelective(form);
		}
		formId=form.getId()+"";
		List<String> ids=new ArrayList<String>();
		for(int i=0;i<arr.size();i++){
			JSONObject obj=arr.getJSONObject(i);
			String name=obj.getString("name");
			String type=obj.getString("type");
			FormFieldInfoExample exa=new FormFieldInfoExample();
			exa.createCriteria().andFieldNameEqualTo(name).andFieldTypeEqualTo(type).andFormIdEqualTo(formId);
			List<FormFieldInfo> list= formFieldInfoMapper.selectByExample(exa);
			FormFieldInfo fieldInfo=null;
			if(list!=null&&list.size()>0){
				fieldInfo=list.get(0);
			}else{
				fieldInfo=new FormFieldInfo();
			}
			fieldInfo.setFormId(formId);
			fieldInfo.setFieldType(obj.getString("type"));
			fieldInfo.setFieldRequired(obj.getBoolean("required")?1:0);
			fieldInfo.setFieldLabel(obj.getString("label"));
			fieldInfo.setClassName(obj.getString("className"));
			fieldInfo.setFieldName(obj.getString("name"));
			fieldInfo.setSubtype(obj.getString("subtype"));
			fieldInfo.setDescription(obj.getString("description"));
			fieldInfo.setPlaceholder(obj.getString("placeholder"));
			fieldInfo.setValue(obj.getString("value"));
			if(StringUtils.isNotBlank(obj.getString("maxlength"))){
				fieldInfo.setMaxlength(obj.getInteger("maxlength"));
			}
			if(StringUtils.isNotBlank(obj.getString("minlength"))){
				fieldInfo.setMinlength(obj.getInteger("minlength"));
			}
			if(StringUtils.isNotBlank(obj.getString("minlength"))){
				fieldInfo.setMinlength(obj.getInteger("minlength"));
			}
			if(StringUtils.isNotBlank(obj.getString("multiple"))){
				fieldInfo.setMultiple(obj.getBoolean("multiple")?1:0);
			}
			if(StringUtils.isNotBlank(fieldInfo.getId())){
				this.updateByPrimaryKeySelective(fieldInfo);
			}else{
				this.insertSelective(fieldInfo);
			}
			if(obj.getJSONArray("values")!=null&&obj.getJSONArray("values").size()>0){
				List<String> valIds=new ArrayList<String>();
				JSONArray valArr=obj.getJSONArray("values");
				for(int j=0;j<valArr.size();j++){
					JSONObject valObj=valArr.getJSONObject(j);
					FormFieldInfoValueExample vexa=new FormFieldInfoValueExample();
					vexa.createCriteria().andFieldValueEqualTo(valObj.getString("value"));
					vexa.createCriteria().andFieldIdEqualTo(fieldInfo.getId());
					List<FormFieldInfoValue> vlist= this.formFieldInfoValueService.selectByExample(vexa);
					FormFieldInfoValue ivalue=null;
					if(vlist==null||vlist.size()==0){
						ivalue=new FormFieldInfoValue();
					}else{
						ivalue=vlist.get(0);
					}
					ivalue.setFieldId(fieldInfo.getId());
					ivalue.setFieldLabel(valObj.getString("label"));
					ivalue.setFieldValue(valObj.getString("value"));
					if(StringUtils.isNotBlank(valObj.getString("selected"))){
						ivalue.setIsSelected(valObj.getBoolean("selected")?1:0);
					}else{
						ivalue.setIsSelected(0);
					}

					if(vlist==null||vlist.size()==0){
						formFieldInfoValueService.insertSelective(ivalue);
					}else{
						formFieldInfoValueService.updateByPrimaryKeySelective(ivalue);
					}
					valIds.add(ivalue.getId());
				}//for(int j=0;j<valArr.size();j++){

				//删除多余的记录
				FormFieldInfoValueExample delexa=new FormFieldInfoValueExample();
				delexa.createCriteria().andFieldIdEqualTo(fieldInfo.getId());
				List<FormFieldInfoValue> dellist= this.formFieldInfoValueService.selectByExample(delexa);
				for(FormFieldInfoValue v:dellist){
					if(!valIds.contains(v.getId())){
						formFieldInfoValueService.deleteByPrimaryKey(v.getId());
					}
				}
			}//if(obj.getJSONArray("values")!=null&&obj.getJSONArray("values").size()>0)
			ids.add(fieldInfo.getId());
		}//for(int i=0;i<arr.size();i++){

		FormFieldInfoExample delfield=new FormFieldInfoExample();
		delfield.createCriteria().andFormIdEqualTo(formId);
		List<FormFieldInfo> delfieldlist= formFieldInfoMapper.selectByExample(delfield);
		for(FormFieldInfo f:delfieldlist){
			if(!ids.contains(f.getId())){
				this.deleteByPrimaryKey(f.getId());
			}
		}
		return form;
	}


	public List<HashMap<String,String>> getFormFieldJson2(String formId){
		FormFieldInfoExample exa=new FormFieldInfoExample();
		exa.createCriteria().andFormIdEqualTo(formId);
		List<FormFieldInfo> fieldList= formFieldInfoMapper.selectByExample(exa);
		List<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>();
		if(fieldList!=null&&fieldList.size()>0){
			for(int i=0;i<fieldList.size();i++){
				HashMap<String,String> map=new HashMap<String,String>();
				FormFieldInfo f=fieldList.get(i);
				map.put("label",f.getFieldLabel() );
				map.put("type",f.getFieldType() );
				map.put("className",f.getClassName() );
				map.put("description",f.getDescription() );
				if(StringUtils.isNotBlank(f.getPlaceholder())){
					map.put("placeholder",f.getPlaceholder() );
				}
				map.put("name",f.getFieldName() );
				if(StringUtils.isNotBlank(f.getValue())){
					map.put("value",f.getValue() );
				}

				map.put("required",f.getFieldRequired()!=null&&f.getFieldRequired()==1?"true":"false" );
				map.put("multiple",f.getMultiple()!=null&&f.getMultiple()==1?"true":"false" );
				map.put("max",f.getFieldMax()+"");
				map.put("min",f.getFieldMin()+"" );
				map.put("step",f.getFieldStep()+"" );
				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 根据表单id获取表单的特定格式的json以用于前端页面动态表单的编辑
	 * @param formId
	 */
	public String getFormFieldJson(String formId){
		FormFieldInfoExample exa=new FormFieldInfoExample();
		exa.createCriteria().andFormIdEqualTo(formId);
		List<FormFieldInfo> fieldList= formFieldInfoMapper.selectByExample(exa);
		StringBuffer sb=new StringBuffer();
		sb.append("[");
		if(fieldList!=null&&fieldList.size()>0){
			for(int i=0;i<fieldList.size();i++){
				FormFieldInfo f=fieldList.get(i);
				sb.append("{");

				sb.append("\"label\":\"");
				sb.append(f.getFieldLabel());
				sb.append("\",");

				sb.append("\"type\":\"");
				sb.append(f.getFieldType());
				sb.append("\",");

				sb.append("\"className\":\"");
				sb.append(f.getClassName());
				sb.append("\",");

				sb.append("\"description\":\"");
				sb.append(f.getDescription());
				sb.append("\",");

				if(StringUtils.isNotBlank(f.getPlaceholder())){
					sb.append("\"placeholder\":\"");
					sb.append(f.getPlaceholder());
					sb.append("\",");
				}

				sb.append("\"name\":\"");
				sb.append(f.getFieldName());
				sb.append("\",");

				if(StringUtils.isNotBlank(f.getValue())){
					sb.append("\"value\":\"");
					sb.append(f.getValue());
					sb.append("\",");
				}

				if(f.getFieldRequired()!=null){
					sb.append("\"required\":");
					sb.append(f.getFieldRequired()==1?"true":"false");
					sb.append(",");
				}
				if(f.getMultiple()!=null){
					sb.append("\"multiple\":");
					sb.append(f.getMultiple()==1?"true":"false");
					sb.append(",");
				}

				if(f.getMaxlength()!=null){
					sb.append("\"maxlength\":");
					sb.append(f.getMaxlength());
					sb.append(",");
				}

				if(f.getFieldMax()!=null){
					sb.append("\"max\":");
					sb.append(f.getFieldMax());
					sb.append(",");
				}

				if(f.getFieldMin()!=null){
					sb.append("\"min\":");
					sb.append(f.getFieldMin());
					sb.append(",");
				}

				if(f.getFieldStep()!=null){
					sb.append("\"step\":");
					sb.append(f.getFieldStep());
					sb.append(",");
				}
				//拼接values字符串
				/*FormFieldInfoValueExample vexa=new FormFieldInfoValueExample();
				vexa.createCriteria().andFieldIdEqualTo(f.getId());
				List<FormFieldInfoValue> vlist= this.formFieldInfoValueService.selectByExample(vexa);
				if(vlist!=null&&vlist.size()>0){
					sb.append("\"values\":[");
					for(int j=0;j<vlist.size();j++){
						FormFieldInfoValue va=vlist.get(j);
						sb.append("{");
						sb.append("\"label\":\"");
						sb.append(va.getFieldLabel());
						sb.append("\",");

						sb.append("\"selected\":");
						sb.append(va.getIsSelected()==1?"true":"false");
						sb.append(",");

						sb.append("\"value\":\"");
						sb.append(va.getFieldValue());
						sb.append("\"");
						sb.append("}");
						if(j<vlist.size()-1){
							sb.append(",");
						}
					}
					sb.append("]");
					sb.append(",");
				}*/

				sb.append("\"subtype\":\"");
				sb.append(f.getSubtype());
				sb.append("\"");

				sb.append("}");
				if(i<fieldList.size()-1){
					sb.append(",");
				}
			}//for(int i=0;i<fieldList.size();i++){

		}//if(fieldList!=null&&fieldList.size()>0){
		sb.append("]");
		return sb.toString();
	}

}
